<template>
  <div>
    <public-modal
      width="660px"
      :footer="false"
      :title="title"
      modalStyle="teenagerProfile"
      :publicVisible="publicVisible"
      @handleOk="handleOk"
      @cancel="cancel"
    >
      <div slot="content" class="form-wrapper">
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          class="form-table-style"
          autocomplete="off"
          layout="inline"
          labelAlign="left"
          :labelCol="{ style: 'width: 120px' }"
        >
          <a-row type="flex" style="height: 2.2rem">
            <a-col flex="1" style="display: flex; flex-direction: column; height: 100%">
              <a-row type="flex" style="flex: 1">
                <a-col flex="auto">
                  <a-form-model-item label="身份证号" prop="idCard" :colon="false">
                    <a-input
                      :maxLength="30"
                      autocomplete="off"
                      placeholder="请填写"
                      v-model="form.idCard"
                      @blur="onIdCardBlur"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row type="flex" style="flex: 1">
                <a-col flex="auto">
                  <a-form-model-item label="人员姓名" prop="name" :colon="false">
                    <a-input :maxLength="30" autocomplete="off" placeholder="请填写" v-model="form.name" />
                  </a-form-model-item>
                </a-col>
                <!--  <a-col flex="360px">
                  <a-form-model-item label="身份证号" prop="idCard" :colon="false">
                    <a-input :maxLength="30" autocomplete="off" placeholder="请输入" v-model="form.idCard" />
                  </a-form-model-item>
                </a-col> -->
              </a-row>

              <a-row type="flex" style="flex: 1">
                <a-col flex="auto">
                  <a-form-model-item label="民族" prop="nation" :colon="false">
                    <a-select allowClear v-model="form.nation" placeholder="请选择">
                      <a-select-option :value="item.value" v-for="(item, index) in nationList" :key="index">
                        {{ item.text }}</a-select-option
                      >
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <!--  <a-col flex="360px">
                  <a-form-model-item label="血型" prop="bloodType" :colon="false">
                    <a-select allowClear v-model="form.bloodType" placeholder="请选择">
                      <a-select-option :value="item.value" v-for="(item, index) in bloodList" :key="index">
                        {{ item.text }}</a-select-option
                      >
                    </a-select>
                  </a-form-model-item>
                </a-col> -->
              </a-row>

              <a-row type="flex" style="flex: 1">
                <a-col flex="auto">
                  <a-form-model-item label="政治面貌" prop="politicalStatus" :colon="false">
                    <a-select allowClear v-model="form.politicalStatus" placeholder="请选择">
                      <a-select-option :value="item.value" v-for="(item, index) in politicalList" :key="index">
                        {{ item.text }}</a-select-option
                      >
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row type="flex" style="flex: 1">
                <a-col flex="auto">
                  <a-form-model-item label="性别" prop="sex" :colon="false">
                    <a-select allowClear v-model="form.sex" placeholder="请选择">
                      <a-select-option :value="item.value" v-for="(item, index) in sexList" :key="index">
                        {{ item.text }}</a-select-option
                      >
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-col>
            <a-col flex="1" style="display: flex; flex-direction: column; height: 100%">
              <a-form-model-item
                label="人脸照片"
                :colon="false"
                style="flex: 1; display: flex; width: 100%"
                class="upload-item"
              >
                <a-upload
                  :file-list="fileList"
                  name="avatar"
                  list-type="picture-card"
                  style="width: 100%; height: 100%"
                  class="avatar-uploader"
                  :customRequest="customRequest"
                  ref="uploadImgRef"
                  :remove="remove"
                  @preview="handlePreview(imageUrl)"
                >
                  <div v-if="fileList.length < 1">
                    <img alt="" class="pictIcon" src="@/assets/imgs/pict-icon.png" />
                    <p class="imgText">点击上传</p>
                  </div>
                </a-upload>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="联系电话" :colon="false">
                <a-input :maxLength="11" autocomplete="off" placeholder="请填写" v-model="form.phone" />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="户籍地址" prop="homeAddress" :colon="false">
                <a-input :maxLength="30" autocomplete="off" placeholder="请填写" v-model="form.homeAddress" />
              </a-form-model-item>
            </a-col>
            <!--  <a-col flex="auto" class="right-box-width">
              <a-form-model-item label="现居地址" :colon="false">
                <a-input
                  :maxLength="30"
                  autocomplete="off"
                  placeholder="请输入"
                  v-model="form.responsibleOrganization"
                />
              </a-form-model-item>
            </a-col> -->
          </a-row>

          <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="现居地址" :colon="false" prop="address">
                <a-input :maxLength="30" autocomplete="off" placeholder="请填写" v-model="form.address" />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="所属派出所" prop="policeAgencyName" :colon="false">
                <a-input :maxLength="30" autocomplete="off" placeholder="请填写" v-model="form.policeAgencyName" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <!--  <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="管控单位类型" prop="policeAgencyName" :colon="false">
                 <a-select allowClear v-model="form.nation" placeholder="请选择">
                      <a-select-option :value="item.value" v-for="(item, index) in controlUnitList" :key="index">
                        {{ item.text }}</a-select-option
                      >
                    </a-select>
                
              </a-form-model-item>
            </a-col>
          </a-row> -->
          <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="关爱原因" :colon="false">
                <a-textarea :maxLength="30" v-model="form.controlReason" placeholder="请输入关爱原因" />
              </a-form-model-item>
            </a-col>
          </a-row>

          <!--  <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="所属责任区" prop="policeJurisdictionId" :colon="false">
                <a-input
                  :maxLength="30"
                  autocomplete="off"
                  placeholder="请填写"
                  disabled
                  v-model="form.policeJurisdictionId"
                />
              </a-form-model-item>
            </a-col>
          </a-row> -->
          <a-row type="flex">
            <a-col flex="1">
              <a-form-model-item label="人员标签" prop="cascader_value" :colon="false">
                <!--  <a-select v-model="form.youthType" ref="select" show-search placeholder="请选择">
                  {{ item }}
                  <a-select-option :value="item.value" v-for="(item, index) in fiveList" :key="index">{{
                    item.text
                  }}</a-select-option>
                </a-select> -->
                <el-cascader
                  style="width: 100%; height: auto"
                  clearable
                  class="cascader"
                  ref="cascader"
                  placeholder="请选择"
                  v-model="form.cascader_value"
                  :options="cascader_options"
                  @change="cascader_change"
                  :props="{ multiple: true, expandTrigger: 'hover' }"
                ></el-cascader>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </public-modal>
  </div>
</template>

<script>
import { uploadFile } from '@/api/api'
import { checkIDCard } from '@/utils/validate.js'
import publicModal from '@/components/publicModal'
import { putAction, postAction } from '@/api/manage'
import { isMobile } from '@/utils/validate'
import { getDictItemsFromCache, ajaxGetDictItems, getKeynoteInfo } from '@/api/api'
import { getPrefixImg, previewImage, under18 } from '../../../../utils/util'
import moment from 'moment'
import { Cascader, Select, Option } from 'element-ui'
import { getAction, getFileAccessHttpUrl } from '../../../../api/manage'

export default {
  name: 'addTeeagerModal',
  components: { publicModal, 'el-cascader': Cascader, 'el-select': Select, 'el-option': Option },
  props: {
    institution: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      title: '新增',
      record: {},
      status: 0,
      publicVisible: false,
      controlUnitList: [
        { text: '户籍地管控', value: 1 },
        { text: '现住地管控', value: 2 },
        { text: '双列管', value: 3 },
      ],

      fileList: [],
      lastNode: [],
      lastNodeList: [],
      showUploadList: { showPreviewIcon: false },
      form: {
        cascader_value: [],
      },
      cascader_options: [],
      cascader_value: [],
      rules: {
        idCard: [
          { required: true, message: '请输入身份证号!' },
          {
            validator: (rule, value, callback) => {
              if (!checkIDCard(value)) {
                callback(new Error('请输入正确的身份证号'))
              } else {
                callback()
              }
            },
          },
        ],
        name: [{ required: true, message: '请输入姓名!' }],

        nation: [{ required: true, message: '请选择民族!' }],
        /*  politicalStatus: [{ required: true, message: '请选择政治面貌!' }], */
        sex: [{ required: true, message: '请选择性别!' }],
        /*  phone: [{ required: true, message: '请输入手机号码!' }], */

        homeAddress: [{ required: true, message: '请输入户籍地址!' }],

        address: [{ required: true, message: '请输入现居地址!' }],
        policeAgencyName: [{ required: true, message: '所属派出所不能为空!' }],
        cascader_value: [{ required: true, message: '请输入人员标签' }],
        // imageUrl: [{ required: true, message: '请上传图片!' }],
      },
      politicalList: getDictItemsFromCache('political_outlook'),
      nationList: getDictItemsFromCache('nation'),

      sexList: getDictItemsFromCache('sex_type'),
      actionType: '',
      uploadImgRef: null,
      imgPrefix: getPrefixImg(),
      youthTypeValues: '',
    }
  },
  inject: ['provideData'],

  mounted() {
    this.getFiveList()
  },
  methods: {
    // * 处理行业树 将children:[] 项过滤
    process_cascader_data(data) {
      if (!data || !Array.isArray(data)) {
        return null
      }
      return data.map((item) => {
        const processedItem = {
          parentId: item.t.parentId,
          label: item.t.dictName,
          value: item.t.dictCode,
          children: item.children.length > 0 ? item.children : null, // 将 children 设置为 null
        }

        if (item.children && item.children.length > 0) {
          processedItem.children = this.process_cascader_data(item.children) // 递归处理子节点
        }

        return processedItem
      })
    },
    /*  async getFiveList() {
      let { result } = await ajaxGetDictItems({ code: 'five_green_types' })
      this.fiveList = result
    }, */
    async getFiveList() {
      let { result } = await getAction('/sysMultiLevelDict/selectSysMultiLevelDictList', { dictCode: 'PREVENT_CRIME' })
      console.log(result, 'result')
      let final_result = this.process_cascader_data(result[0].children)
      console.log(final_result, 'final_result')

      this.cascader_options = final_result
    },
    // * 级联选择框变化时触发
    cascader_change(e) {
      console.log(this.form.cascader_value, 'bangdingzhi')

      const lastItems = this.form.cascader_value.map((path) => path[path.length - 1])
      this.youthTypeValues = lastItems.join(',')

      console.log(e[0], '选中节点', this.youthTypeValues)
      //let click_node_id_list = []
      // this.$refs.cascader.getCheckedNodes().forEach((item) => {
      //   click_node_id_list.push(item.value)

      // })
      // console.log(this.$refs.cascader.getCheckedNodes(true), '方法名') //只选最深的节点
      // this.lastNodeList = this.$refs.cascader.getCheckedNodes(true)
      // this.lastNode = lastNode.map((item) => {
      //   return { label: item.label, value: item.value }
      // })
      // this.lastNodeList.push(this.lastNode)
      // console.log(this.lastNodeList, 'lastNodeList8888')

      //  this.form.youthType = this.lastNode[0].value
    },
    /**
     * 根据叶子节点 value，反查完整路径
     * @param {Array} tree - cascader_options
     * @param {string} targetValue - 叶子节点 value， "PMFC-2"
     * @returns {Array|null} - 返回完整路径， ['ROOT', 'PMFC', 'PMFC-2']
     */
    findPathByLeafValue(tree, targetValue) {
      const path = []

      const dfs = (nodes) => {
        for (const node of nodes) {
          path.push(node.value)
          if (node.value === targetValue) return [...path]
          if (node.children) {
            const found = dfs(node.children)
            if (found) return found
          }
          path.pop()
        }
        return null
      }

      for (const root of tree) {
        const result = dfs([root])
        if (result) return result
      }
      return null
    },
    async show(record = {}, actionType = 'add') {
      this.actionType = actionType
      this.record = record
      this.publicVisible = true

      if (actionType == 'edit') {
        this.title = `编辑人员`
        this.form = { ...record, sex: String(record.sex) }
        console.log(this.form, '怒良行为')
        console.log(this.form.youthType, 'youthtype')
        const leafValues = this.form.youthType.split(',').map((item) => item.trim())
        console.log(leafValues, '也直接点')
        this.form.cascader_value = leafValues.map((value) => {
          const path = this.findPathByLeafValue(this.cascader_options, value)
          return path || [value]
        })

        if (record.minorImage) {
          const obj = {
            uid: record.minorImage,
            name: record.minorImage,
            status: 'done',
            url: this.imgPrefix + record.minorImage,
          }
          this.fileList = [obj]
          this.imageUrl = [{ halfPath: record.minorImage }]
        }
      } else {
        this.title = `新增人员`
        this.$set(this.form, 'policeAgencyName', this.institution.policeAgencyName)
      }
    },
    async onIdCardBlur() {
      const idCard = this.form.idCard?.trim()
      if (!idCard) return
      // 1. 前端快速校验
      if (!checkIDCard(idCard)) {
        this.$message.warn('身份证号格式不正确')
        return
      }

      try {
        const res = await getKeynoteInfo({ data: { sfzh: idCard } })
        if (res.code !== 200 || !res.result) {
          this.$message.warn(res.message || '未查到相关信息')
          return
        }
        // 3. 回填（字段名按你实际接口调整）
        const info = res.result
        console.log(info, 'info')
        const sex_value = info.xb == '男' ? '1' : '2'
        // 方式 A：只填几个字段
        this.$set(this.form, 'name', info.xm || '')
        this.$set(this.form, 'sex', sex_value) // 0/1 转字符串
        this.$set(this.form, 'nation', info.mz || '')
        this.$set(this.form, 'homeAddress', info.jzdxz || '')
        // 方式 B：整体合并（注意不要把 cascader_value 覆盖掉）
        // this.form = Object.assign({}, this.form, info)
      } catch (e) {
        console.error(e)
        this.$message.error('查询失败，请稍后重试')
      }
    },

    remove(file) {
      console.log('remove')
      let uid = file.uid
      let index = this.fileList.findIndex((v) => {
        return v.uid == uid
      })
      this.fileList.splice(index, 1)
      this.imageUrl.splice(index, 1)
      // 上传完成之后，隐藏上传框
      let uploadDom = this.$refs.uploadImgRef.$el.getElementsByClassName('ant-upload-select-picture-card')[0]
      uploadDom.style.display = 'flex'
    },
    async customRequest(info) {
      console.log(info, '上传')
      let file = info.file
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 2)
      let res = await uploadFile(formData)
      if (res.code == 200) {
        this.imageUrl = [res.result]
        //this.imageUrl.push(res.result.halfPath)
        this.form.imageUrl = [res.result.halfPath]
        this.fileList = [res.result].map((item, index) => {
          return {
            uid: index,
            status: 'done',
            url: item.fullPath,
          }
        })

        // 上传完成之后，隐藏上传框
        let uploadDom = this.$refs.uploadImgRef.$el.getElementsByClassName('ant-upload-select-picture-card')[0]
        uploadDom.style.display = 'none !important'
      }
    },
    uploadChange({ file, fileList }) {
      file.status = 'done'
      this.fileList = fileList
    },

    handleOk() {
      console.log('dianjiqueding ')
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        //  if (!this.fileList.length) return this.$message.error('请上传图片！')
        if (!this.form.cascader_value) return this.$message.error('请选择人员标签！')
        /*  if (!under18(this.form.idCard)) {
          return this.$message.error('身份证年龄不能超过18岁')
        } */
        let url = ''
        if (this.actionType == 'add') {
          url = '/qnMinor/addMinor'
        } else {
          url = '/qnMinor/updateMinor'
        }
        const method = this.record.id ? postAction : postAction
        // const youthList = this.lastNodeList.map((item) => item.value)
        // console.log(youthList, 'youthList')
        //  this.form.youthType = youthList.join(',')

        try {
          const res = await method(url, {
            ...this.form,
            policeAgencyId: this.institution.id,
            minorImage: this.imageUrl?.map((item) => item.halfPath).join(','),
            youthType: this.youthTypeValues,

            //judgmentTime: moment(this.form.judgmentTime).format('yyyy/MM/DD HH:mm:ss'),
          })
          this.$message.success(res.message)
          this.$emit('refresh')
          this.cancel()
        } catch (error) {
          // 处理错误
          console.error('请求失败:', error)
          this.$message.error('请求失败，请稍后重试！')
        }
      })
    },
    handleAdd() {
      this.$refs.addRef.show()
    },

    cancel() {
      this.publicVisible = false
      this.fileList = []
      this.imageUrl = []
      this.form = {}
    },
    handlePreview(urls = []) {
      urls = urls.map((item) => item.halfPath)
      previewImage.call(this, urls)
    },
  },
}
</script>

<style scoped lang="less">
.form-row {
  display: flex;

  flex-wrap: nowrap; /* 禁止换行 */

  align-items: flex-start; /* 顶部对齐 */
}
.cascader {
}
.picture.ant-col {
  display: flex;
  /deep/ .ant-form-item-label {
    height: 195px !important;
    border-right: none !important;
    line-height: 195px;
    text-align: center;
  }
}
.formStyle {
  padding: 0.2rem;
  /deep/.ant-col {
    height: unset;
  }
  .ant-form-inline .ant-form-item-with-help {
    margin-bottom: 5px;
  }
}
.form-wrapper {
  padding: 32px 25px 20px 25px;
  .upload-item {
    /deep/ .ant-form-item-control-wrapper {
      border: 1px solid #0855cc;
    }
  }

  .form-table-style {
    /deep/.ant-form-item-label {
      background: #084dbe;
      border: 1px solid #0855cc;
      padding-left: 12px;
      height: 100%;
      flex-shrink: 0;
      > label {
        font-weight: 500;
        font-size: 14px;
        color: #8fbbff;
      }
    }
    /deep/.avatar-uploader {
      height: 100% !important;
      display: flex !important;
      align-items: center;
      justify-content: center;
      position: relative;

      > .ant-upload {
        width: 100%;
        height: 100%;
        background: transparent;
        border: none;
      }
    }
    /deep/ .ant-upload-list-item {
      width: 160px;
      height: 160px;
      position: absolute;
      top: 28px;
      right: 14px;
    }

    .imgText {
      color: #1163b8;
      font-weight: 500;
    }
    .pictIcon {
      margin-bottom: 10px;
      width: 42px;
      height: 38px;
    }

    /deep/.ant-form-explain {
      position: absolute;
      z-index: 10;
      bottom: -5px;
      left: 10px;
    }
    /deep/.ant-form-item-control-wrapper {
      flex: 1;
      height: 100%;
    }
    /deep/.ant-form-item {
      align-items: stretch;
      margin-right: 0;
      height: 46px;
      display: flex;
    }
    /deep/.ant-form-item-with-help {
      margin-right: 0;
      margin-bottom: 0;
    }
    /deep/.ant-form-item-control {
      height: 100%;
      .ant-form-item-children {
        height: 100%;
        display: block;
        .ant-input {
          height: 100%;
          background: #07429e;
          border-radius: 0px 0px 0px 0px;
          border: 1px solid #0855cc;
          color: #fff;
          &::placeholder {
            color: #6ea7ff;
          }
        }
        .ant-select {
          height: 100%;
          vertical-align: top;
        }

        .ant-calendar-picker {
          height: 100%;
          > div {
            height: 100%;
          }
        }
        .ant-select-selection {
          height: 100%;
          background: #0a49af;
          border: 0;
          border-radius: 0;
        }
        .select-jurisdiction {
          width: 339px;
        }

        .ant-select-selection__rendered {
          height: 100%;
        }
        .ant-select-selection-selected-value {
          line-height: 42px;
          color: #fff;
        }
        .ant-select-selection__placeholder {
          color: #6ea7ff;
        }
      }
    }
    .right-box-width {
      max-width: 480px;
    }
  }
}

.imageUpload {
  margin-bottom: 150px;
  /deep/.avatar-uploader {
    > .ant-upload {
      width: 150px;
      height: 176px;
      background: var(--theme-input-bg);
      border: 1px solid var(--theme-input-border);
    }
  }

  /deep/.ant-upload-select-picture-card {
    width: 150px;
    height: 176px;
  }

  /deep/ .ant-upload-list-item {
    width: 150px;
    height: 176px;
  }

  .imgText {
    color: #1163b8;
    font-weight: 500;
  }

  .pictIcon {
    margin-bottom: 10px;
    width: 42px;
    height: 38px;
  }
}
</style>
